<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'cardd:tbjl:coreCltbjl:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #coreCltbjlbtList>
        <BasicTable @register="registerCoreCltbjlbtTable" @row-click="handleCoreCltbjlbtRowClick" />
        <a-button class="mt-2" @click="handleCoreCltbjlbtAdd" v-auth="'cardd:tbjl:coreCltbjl:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsCarddTbjlCoreCltbjlForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { CoreCltbjl, coreCltbjlSave, coreCltbjlForm } from '/@/api/cardd/tbjl/coreCltbjl';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('cardd.tbjl.coreCltbjl');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<CoreCltbjl>({} as CoreCltbjl);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增车辆投保记录') : t('编辑车辆投保记录'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('车牌号'),
      field: 'cltbjlCph',
      fieldLabel: 'cltbjlCph',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'basCarSelect',
          onSelect: (v) => {
            formModel['cltbjlClsbdm'] = v[0].clsbdh;
            formModel['cltbjlFdjhm'] = v[0].fdjhm;
            formModel['cltbjlZws'] = v[0].zws;
            formModel['cltbjlGcjg'] = v[0].gcjg;
          },
        };
      },
      required: true,
    },
    {
      label: t('车辆识别代码'),
      field: 'cltbjlClsbdm',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('发动机号码'),
      field: 'cltbjlFdjhm',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('购车价格'),
      field: 'cltbjlGcjg',
      component: 'Input',
      componentProps: {
        maxlength: 8,
        disabled: true,
      },
      // rules: [
      //   { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      // ],
    },
    {
      label: t('座位数'),
      field: 'cltbjlZws',
      component: 'Input',
      componentProps: {
        maxlength: 8,
        disabled: true,
      },
      //rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('投保公司'),
      field: 'cltbjlTbgs',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('投保日期'),
      field: 'cltbjlTbrq',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
    },
    {
      label: t('保险到期'),
      field: 'cltbjlBxdq',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
    },
    {
      label: t('保单号'),
      field: 'cltbjlBdh',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('商业险保费'),
      field: 'cltbjlSyxbf',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('交强险保费'),
      field: 'cltbjlJqxbf',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('车船税保费'),
      field: 'cltbjlCcsbf',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('保费总额'),
      field: 'cltbjlBfze',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'Input',
      componentProps: {
        maxlength: 600,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('附件上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'coreCltbjl_file',
        uploadType: 'all',
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'coreCltbjlbtList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'coreCltbjlbtList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 6, md: 24 },
  });

  const [registerCoreCltbjlbtTable, coreCltbjlbtTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleCoreCltbjlbtDelete.bind(this, record),
          },
          auth: 'cardd:tbjl:coreCltbjl:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setCoreCltbjlbtTableData(_res: Recordable) {
    coreCltbjlbtTable.setColumns([
      {
        title: t('保险公司'),
        dataIndex: 'cltbjlbtBxgs',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('保单号'),
        dataIndex: 'cltbjlbtBdh',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('起保时间'),
        dataIndex: 'cltbjlbtQbsj',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('终保时间'),
        dataIndex: 'cltbjlbtZbsj',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('险种'),
        dataIndex: 'cltbjlbtXz',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('险种项目'),
        dataIndex: 'cltbjlbtXzxm',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('保费'),
        dataIndex: 'cltbjlbtBfy',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },
      {
        title: t('保值'),
        dataIndex: 'cltbjlbtBzw',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },
      {
        title: t('发票号码'),
        dataIndex: 'cltbjlbtFphm',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('是否退保'),
        dataIndex: 'cltbjlbtSftb',
        width: 130,
        align: 'center',
        dictType: 'sys_yes_no',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_yes_no',
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('退保日期'),
        dataIndex: 'cltbjlbtTbrq',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: false,
      },
      {
        title: t('退保金额'),
        dataIndex: 'cltbjlbtTbje',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },
      {
        title: t('备注'),
        dataIndex: 'cltbjlbtBz',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
    ]);
    coreCltbjlbtTable.setTableData(record.value.coreCltbjlbtList || []);
  }

  function handleCoreCltbjlbtRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleCoreCltbjlbtAdd() {
    coreCltbjlbtTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleCoreCltbjlbtDelete(record: Recordable) {
    coreCltbjlbtTable.deleteTableDataRecord(record);
  }

  async function getCoreCltbjlbtList() {
    let coreCltbjlbtListValid = true;
    let coreCltbjlbtList: Recordable[] = [];
    for (const record of coreCltbjlbtTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        coreCltbjlbtListValid = false;
      }
      coreCltbjlbtList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of coreCltbjlbtTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      coreCltbjlbtList.push({
        ...record,
        status: '1',
      });
    }
    if (!coreCltbjlbtListValid) {
      throw { errorFields: [{ name: ['coreCltbjlbtList'] }] };
    }
    return coreCltbjlbtList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await coreCltbjlForm(data);
    record.value = (res.coreCltbjl || {}) as CoreCltbjl;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setCoreCltbjlbtTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
        createBy: record.value.createBy,
        createDate: record.value.createDate,
        updateBy: record.value.updateBy,
        updateDate: record.value.updateDate,
      };
      data.coreCltbjlbtList = await getCoreCltbjlbtList();
      // console.log('submit', params, data, record);
      const res = await coreCltbjlSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
